package org.sensation.file.channel.map;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

import org.sensation.file.channel.FileWriteChannel;
import org.sensation.file.channel.SetupToWriteTempFile;

public class FileWriteChannelMap implements FileWriteChannel{
	private MappedByteBuffer targetMap;
	private File file;
	private FileChannel targetChannel;
	
	public FileWriteChannelMap(String targetFilePath, int targetFileSize)
			throws FileNotFoundException, IOException {
		SetupToWriteTempFile tempFile = new SetupToWriteTempFile(targetFilePath, targetFileSize);
		initTargetChannel();
	}

	public void writeFile(ByteBuffer buffer) throws IOException {
		buffer.flip();
		targetChannel.write(buffer);
	}
	
	public void writeIndexAccessFile(int offset, ByteBuffer buffer) throws IOException{
		byte[] data = buffer.array();
		for(int index=0; index < buffer.limit(); index++)
			targetMap.put(index+offset, data[index]);
		targetMap.force();
	}
	
	private void initTargetChannel() throws IOException, FileNotFoundException {
		RandomAccessFile raf = new RandomAccessFile(file, "rw");
		targetChannel = raf.getChannel();
		targetMap = targetChannel.map(MapMode.READ_WRITE, 0, targetChannel.size());
	}

	public void close() throws IOException {
		
	}
}
